<template>
  <div class="users">

    <div class="select">
      <ToolBar :show-all="false" :show-multiple="false" :delete-disable="multipleSelection.length===0" :delete-data="deleteById" :update-data="updateById" :update-disable="multipleSelection.length!==1" :add-data="setAddDialogVisible" :add-batch-data="addBatchData"></ToolBar>
      <el-form :inline="true" style="margin-left: 1rem">
        <el-form-item label="员工姓名：">
          <el-select v-model="form.jobNumber" placeholder="请选择员工姓名..."  value-key="id"  filterable clearable size="small">
            <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.jobNo" v-for="item in $store.state.userList" :key="item.id">
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item> <el-button type="primary" @click="handleCurrentChange(1)"  size="small">筛选</el-button></el-form-item>

      </el-form>
    </div>
    <el-table

        border
        :data="tableData"
        :header-cell-style="{'text-align':'center'}"
        @selection-change="handleSelectionChange"
        :cell-style="{'text-align':'center'}">
      <el-table-column type="selection" width="50" label="序号">
      </el-table-column>
      <el-table-column
          prop="username"
          label="账号">
      </el-table-column>
      <el-table-column
          label="角色" sortable="true" min-width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.role" v-text="scope.row.role.introduction"></el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名">
      </el-table-column>
      <el-table-column
          prop="jobNumber"
          label="工号">
      </el-table-column>
      <el-table-column
          prop="position"
          min-width="120"
          label="职位">
      </el-table-column>
      <el-table-column
          label="性别">
        <template slot-scope="scope">
          <el-tag v-text="scope.row.sex?'男':'女'" :type="scope.row.sex?'':'danger'"></el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="telephone"
          min-width="140"
          label="手机号码">
      </el-table-column>
      <el-table-column
          prop="email"
          min-width="150"
          label="用户状态">
        <template slot-scope="scope">
          <!--          <el-tag :type="scope.row.delete?'danger':''"><span v-text="scope.row.delete?'停用':'正常'"></span></el-tag>-->
          <el-switch
              v-model="scope.row.enabled"
              :active-value="true"
              :inactive-value="false" @change="statusExchange(scope.row,!scope.row.enabled)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
          prop="email"
          min-width="100"
          label="是否使用">
        <template slot-scope="scope">
                    <el-tag :type="scope.row.first?'danger':''"><span v-text="scope.row.first?'否':'是'"></span></el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="其他信息"
          width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" v-if="scope.row.createUser">
<!--            <p>创建者: {{ scope.row.createUser.name }}</p>-->
            <p>创建时间: {{ scope.row.createdTime|formatDate }}</p>
<!--            <p>更新者: {{ scope.row.updateUser.name }}</p>-->
            <p>更新时间: {{ scope.row.updateTime|formatDate }}</p>
            <p>最近登录IP: <span v-text="scope.row.ip"></span></p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button
              size="mini" type="warning"
              @click="resetPassword(scope.row.username)">密码重置
          </el-button>
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              :disabled="scope.row.id===$store.state.userInfo.id&&$store.state.userInfo"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-dialog :title="'用户信息'+operationType" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="ruleForm" ref="form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" :label-width="formLabelWidth" prop="name">
              <el-input v-model="form.name" autocomplete="off" @blur="verifyUserName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录账号" :label-width="formLabelWidth" prop="username">
              <el-input v-model="username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户工号" :label-width="formLabelWidth" prop="jobNumber">
              <el-input v-model="form.jobNumber" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户职位" :label-width="formLabelWidth">
              <el-input v-model="form.position" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" :label-width="formLabelWidth">
              <el-input v-model="form.telephone" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" :label-width="formLabelWidth" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户角色" :label-width="formLabelWidth">
              <el-select v-model="form.roleId" class="w100" :disabled="form.id===$store.state.userInfo.id&&form.role.roleLevel>1">
                <el-option v-for="item in roleList" :lablel="item.introduction" :key="item.id"
                           :label="item.introduction"
                           :value="item.id">

                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false,form={}">取 消</el-button>
        <el-button type="primary" @click="add" v-if="operationType==='添加'" >确定<span v-text="operationType"></span></el-button>
        <el-button type="primary" @click="edit" v-if="operationType==='修改'">确定<span v-text="operationType"></span></el-button>

      </div>
    </el-dialog>
    <el-dialog
        top="15vh"
        :visible.sync="userDialog"
        width="50%"
        title="用户批量导入"
        :before-close="handleClose"
        center>
      <el-upload
          class="upload-demo"
          drag
          :http-request="uploadUsers"
          auto-upload
          accept=".xlsx,.xls"
          multiple action="#" style="text-align: center!important;">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传1个.xls/.xlsx文件</div>

        <el-link type="success" href="https://47.109.16.23:28361/down/GURX6ipYziXs.xlsx" style="margin-top: 1rem">点击下载用户上传模板</el-link>
      </el-upload>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible" append-to-body center>
      <div slot="title">
        <h3>提示</h3>
        <h5>上传文件中：
          <el-tag type="info" v-text="allNum"></el-tag>
          条数据，成功导入
          <el-tag type="success" v-text="successNum"></el-tag>
          条数据，失败导入：
          <el-tag type="danger" v-text="errorNum"></el-tag>
          条数据<span v-if="errorNum>0">，错误信息如下：</span></h5>
      </div>
      <el-row>
        <ol v-if="list.length>0" style="text-align: center;height:35vh;overflow-y: scroll;">
          <li v-for="(item,index) in list" style="text-align: left;">
            <span v-text="item" style="width: 350px;overflow: hidden;text-overflow: ellipsis"></span></li>
        </ol>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";

export default {
  name: "Users",
  components: {ToolBar},
  data() {
    return {
      allNum: 0,
      successNum: 0,
      errorNum: 0,
      list:[],
      dialogVisible:false,
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      dialogFormVisible: false,
      form: {
        name: null,
        jobNumber: null,
        position: null,

      },
      ruleForm: {
        "name": [{required:true,message: "请输入用户姓名...", trigger: "blur"}],
        "jobNumber": [{required:true,message: "请输入用户工号...", trigger: "blur"}],
        "sex":[{required:true,message: "请选择性别...", trigger: "change"}],
        // "email":[{required:true,message: "请输入邮箱...", trigger: "change"}]
      },
      formLabelWidth: '120px',
      roleList:[],
      operationType:"添加",
      isDisabled:false,
      username:null,
      userDialog:false,
      dingUsersList:[],
      multipleSelection: [],
    }
  },
  created() {
    this.getDataList()
    this.getUserList1()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getUserList1() {
      axios.get("/fin_user_roster/list").then(res => {
        this.finUserRosterList = res.data.data
        this.$store.commit("setUserList",this.finUserRosterList)
        Object.freeze(this.finUserRosterList)
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    addBatchData(){
      console.log("批量添加")
      this.userDialog=true
    },
    uploadUsers(res){
      console.log(res)
      let formData = new FormData();
      formData.append("file", res.file)
      axios({
        method: "POST",
        url: "/user/addBatch/"+this.$store.state.userInfo.id,
        headers: {
          'content-type': 'multipart/form-data',
        },
        data: formData
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          let successNum = parseInt(res.data.data.successNum);
          let errorNum = parseInt(res.data.data.errorNum);
          let allNum = successNum + errorNum
          if (errorNum > 0) {
            let list = res.data.data.list
            this.successNum = successNum;
            this.errorNum = errorNum
            this.allNum = allNum;
            this.list = list
            this.dialogVisible = true
          } else {
            this.personalAmount=false
            this.getDataList()
            this.$message({
              dangerouslyUseHTMLString: true,
              message: "成功上传<b>" + allNum + "</b>条数据",
              type: "success"
            })
          }
        }
        else {
          this.$message({
            dangerouslyUseHTMLString: true,
            message: res.data.message,
            type: "error"
          })
        }
      })
    },
    verifyUserName(){
      let username=null
      axios.post("/user/verify",this.form).then(res=>{
        if(!res.data.success){
          this.$tools.showMessage("已存在同名用户！","error")
          this.isDisabled=true
        }else{
          console.log("UserRes:",res)
          this.isDisabled=false
          this.username=res.data.data.username
        }
      })

    },
    handleEdit(index, row) {
      this.operationType="修改"
      console.log(index, row);
      this.getRoleList()
      this.form=row
      this.username=row.username
      this.dialogFormVisible = true
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$tools.showMessageBox("确认删除用户："+row.name+"？","提示","warning").then(confirm=>{
        axios.post("/user/delete/"+this.$store.state.userInfo.id+"/"+this.$store.state.userInfo.name,row).then(res=>{
          if(res.data.success){
            this.$tools.showMessage("删除成功！","success")
            this.getDataList()
          }else{
            this.$tools.showMessage("删除失败！","error")
          }
        })
      }).catch(cancel=>{
        this.$tools.showMessage("操作取消！","info")
      })
    },
    getDataList() {
      axios.post("/user/list/" + this.currentPage + "/" + this.size,this.form).then(res => {
        console.log("用户列表：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        }else{
          this.$tools.showMessage("暂无当前用户","warning")
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    deleteById() {
      this.$tools.showMessageBox("确认删除"+this.multipleSelection.length+"条用户数据？","批量删除确认","warning").then(confirm=>{
        axios.post("/user/deleteBatch/"+this.$store.state.userInfo.id+"/"+this.$store.state.userInfo.name,this.multipleSelection).then(res=>{
          console.log("批量删除结果：",res)
          if(res.data.success){
            this.$tools.showMessage(res.data.message,"success")
            this.getDataList()
          }else{
            this.$tools.showMessage(res.data.message,"error")
          }
        })
      }).catch(cancel=>{
        this.$tools.showMessage("操作已取消！","info")
      })
    },
    updateById() {
      console.log("用户修改")
      this.form=this.multipleSelection[0]
      this.handleEdit(0,this.form)
    },
    setAddDialogVisible() {
      this.operationType="添加"
      this.form={}
      this.username=null
      this.getRoleList()
      this.dialogFormVisible = true
    },
    edit(){
      this.form.username=this.username
      this.form.updateUserId=this.$store.state.userInfo.id
      axios.post("/user/update",this.form).then(res=>{
        if(res.data.success){
          this.$tools.showMessage("修改成功！","success")
          this.dialogFormVisible=false
          this.form={}
          this.getDataList()
        }else{
          this.$tools.showMessage("修改失败！","success")
        }
      })
    },
    statusExchange(row,enabled){
      console.log(row)
      row.enabled=row.enabled.valueOf()
      console.log("Roe:",row)
      let message="确认修改"+row.name+"("+row.jobNumber+")的状态为："+(row.enabled?'可用':'不可用')
      this.$tools.showMessageBox(message,"操作确认","warning").then(confirm=>{
        axios.post("/user/status/"+this.$store.state.userInfo.id+"/"+this.$store.state.userInfo.name,row).then(res=>{
          if(res.data.success){
            this.$tools.showMessage(res.data.message,"success")
          }else{
            this.$tools.showMessage(res.data.message,"error")

          }
        })
      }).catch(cancel=>{
      this.$tools.showMessage("操作取消！","info")
      })
    },
    add() {
      console.log('用户添加')
      this.form.username=this.username
      this.form.createUserId=this.$store.state.userInfo.id
      axios.post("/user/add",this.form).then(res=>{
        if(res.data.success){
          this.$tools.showMessage("添加成功！","success")
          this.dialogFormVisible=false
          this.form={}
          this.getDataList()
        }else{
          this.$tools.showMessage("添加失败！","error")

        }
      })
    },
    getRoleList(){
      axios.post("/roles/list").then(res=>{
        if(res.data.success){
          this.roleList=res.data.data
          console.log("所有角色：",res.data.data)
        }else{
          this.roleList=[]
        }
      })
    },
    resetPassword(username){
      this.$tools.showMessageBox("确认重置密码？重置后密码与登录名相同","操作确认","warning").then(confirm=>{

        axios.post("/user/resetPassword/"+username).then(res=>{
          if(res.data.success){
            this.$tools.showMessage("密码重置成功！","success")
          }else{
            this.$tools.showMessage(res.data.message,"error")

          }
        })
      }).catch(cancel=>{
        this.$tools.showMessage("操作取消！","info")
      })

    }
  }
}
</script>

<style lang="less">
.users{
  .select{
    display: inline-flex;
  }
}
</style>
